﻿using AutoMapper;
using B.S.BasicData.Api.Read.Application.Command.Area;
using B.S.BasicData.Api.Read.Dtos;
using B.S.BasicData.Domain.Entities;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interface;
using MediatR;
using System.Collections.Generic;

namespace B.S.BasicData.Api.Read.Application.CommandHandler.Area
{
    /// <summary>
    /// 查询区域树状数据结构的处理类
    /// </summary>
    public class GetAreaTreeHandler : IRequestHandler<GetAreaTreeCommand, ApiResult<List<AreaTreeDto>>>
    {
        private readonly IBaseRepository<AreaModel> areaRepo;
        private readonly IMapper mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="areaRepo">区域仓储</param>
        /// <param name="mapper">Automapper</param>
        public GetAreaTreeHandler(IBaseRepository<AreaModel> areaRepo,IMapper mapper)
        {
            this.areaRepo = areaRepo;
            this.mapper = mapper;
        }
        /// <summary>
        /// 查询区域树状数据结构的处理方法
        /// </summary>
        /// <param name="request">请求命零</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>Task包装的区域的树状列表</returns>
        public Task<ApiResult<List<AreaTreeDto>>> Handle(GetAreaTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<AreaTreeDto>> result = new ApiResult<List<AreaTreeDto>>();
            result.Msg = "查询区域树状结构数据成功!";
            result.Code = ApiEnums.Success;
            result.Data = GetAreaTree(0);
            return Task.FromResult(result);
        }
        /// <summary>
        /// 递归查询区域数据
        /// </summary>
        /// <param name="parentId">区域父级id</param>
        /// <returns>父子层级的区域列表</returns>
        private List<AreaTreeDto> GetAreaTree(long parentId)
        {
            var areas = areaRepo.GetAll().Where(x => x.ParentId == parentId);
            var areaDtos = mapper.Map<List<AreaTreeDto>>(areas);  //因为有amp转换,所以需要配置AutoMap Profile
            foreach (var item in areaDtos)
            {
                item.Children = GetAreaTree(item.Id);   //mapper.Map<List<AreaTreeDto>>(areaRepo.GetAll().Where(x => x.ParentId == item.Id));
            }
            return areaDtos;
        }
    }
}
